const fetch = require('../../utils/fetch')
Page({
  data: {
    // 当前加载的分类
    category: {},
    // 此分类下的店铺
    shops: [],
    pageIndex: 0,
    pageSize: 10,
    isHasText: true
  },
  /*生命周期函数--监听页面加载*/
  onLoad: function (options) {
    fetch(`categories/${options.cat}`).then(res => {
      this.setData({ category: res.data })
      wx.setNavigationBarTitle({ title: res.data.name })
      // 加载完分类信息过后再去加载商铺信息
      this.loadMore()
    })
  },
  loadMore: function() {
    let { pageIndex, pageSize } = this.data
    return fetch(`categories/${this.data.category.id}/shops`, { _page: ++pageIndex, _limit: pageSize })
    .then(res => {
      if (this.data.shops.length === Number(res.header['x-total-count'])) {
        this.setData({ isHasText: false })
        return
      }
      const shops = this.data.shops.concat(res.data)
      this.setData({ shops: shops })
    })
  },
  /*生命周期函数--监听页面初次渲染完成*/
  onReady: function () {
    if (this.data.category.name) {
      wx.setNavigationBarTitle({ title: this.data.category.name })
    }
  },
  /* 页面上拉触底事件的处理函数 */
  onReachBottom: function () {
    // 在这一页加载下一页的数据
    if (this.data.isHasText) {
      ++this.data.pageIndex
      this.loadMore()
    }
  },
 /*页面相关事件处理函数--监听用户下拉动作*/
  onPullDownRefresh: function () {
    // 重新加载数据
    this.setData({
      shops: [],
      pageIndex: 0,
      isHasText: true
    })
    this.loadMore().then( () => {
      wx.stopPullDownRefresh()
    } )
  }
})